<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getCoursesManage, deleteCourse } from '../../services/api';

const router = useRouter();
const courses = ref([]);
const loading = ref(true);
const error = ref(null);
const deleteLoading = ref(false);

// 分页相关状态
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载课程数据
const loadCourses = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    const data = await getCoursesManage(pageNum.value, pageSize.value);
    courses.value = data.courseList || [];
    total.value = data.total || 0;
    // 不从响应中更新pageNum，保持用户选择的页码
    pageSize.value = data.pageSize || 10;
  } catch (err) {
    error.value = '获取课程列表失败';
    console.error(err);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadCourses();
});

// 页码变化处理
const handlePageChange = (newPage) => {
  pageNum.value = newPage;
  loadCourses();
};

const handleEdit = (courseId) => {
  router.push(`/admin/upload?id=${courseId}`);
};

const handleDelete = async (courseId) => {
  if (confirm('确定要删除这个课程吗？')) {
    try {
      deleteLoading.value = true;
      const success = await deleteCourse(courseId);
      if (success) {
        // 删除成功后重新加载当前页数据
        loadCourses();
      } else {
        alert('删除课程失败，请稍后重试');
      }
    } catch (err) {
      console.error('删除课程出错:', err);
      alert('删除课程失败，请稍后重试');
    } finally {
      deleteLoading.value = false;
    }
  }
};
</script>

<template>
  <div>
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold text-gray-800">课程管理</h2>
      <router-link 
        to="/admin/upload" 
        class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
      >
        添加新课程
      </router-link>
    </div>
    
    <div v-if="loading" class="text-center py-10">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-500 border-t-transparent"></div>
      <p class="mt-2 text-gray-600">加载中...</p>
    </div>
    
    <div v-else-if="error" class="bg-red-100 p-4 rounded-md text-red-700">
      {{ error }}
    </div>
    
    <div v-else-if="courses.length === 0" class="text-center py-10">
      <p class="text-gray-500">暂无课程数据</p>
    </div>
    
    <div v-else>
      <!-- 表格视图 - 更适合管理界面 -->
      <div class="overflow-x-auto bg-white rounded-lg shadow">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程信息</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排序</th>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="course in courses" :key="course.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-16 w-24 relative">
                    <img 
                      :src="course.coverUrl" 
                      alt="课程封面" 
                      class="h-full w-full object-cover rounded"
                      @error="e => e.target.src = 'https://picsum.photos/id/42/400/300'"
                    />
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ course.title }}</div>
                    <div class="text-sm text-gray-500 line-clamp-1">{{ course.description }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span v-if="course.status === 1" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">已上线</span>
                <span v-else-if="course.status === 0" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">未上线</span>
                <span v-else-if="course.status === 2" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">草稿</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ new Date(course.createTime).toLocaleDateString() }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ course.sortOrder }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <button 
                  @click="handleEdit(course.id)" 
                  class="text-blue-600 hover:text-blue-900 mr-3"
                >
                  编辑
                </button>
                <button 
                  @click="handleDelete(course.id)" 
                  class="text-red-600 hover:text-red-900"
                  :disabled="deleteLoading"
                >
                  {{ deleteLoading ? '删除中...' : '删除' }}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页组件 -->
      <div v-if="!loading && !error && courses.length > 0" class="mt-6 flex justify-center">
        <div class="flex items-center space-x-2">
          <button 
            @click="handlePageChange(pageNum - 1)" 
            :disabled="pageNum <= 1"
            class="px-3 py-1 rounded border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            上一页
          </button>
          
          <div class="px-4 py-1">
            第 {{ pageNum }} 页 / 共 {{ Math.ceil(total / pageSize) }} 页
          </div>
          
          <button 
            @click="handlePageChange(pageNum + 1)" 
            :disabled="pageNum >= Math.ceil(total / pageSize)"
            class="px-3 py-1 rounded border border-gray-300 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            下一页
          </button>
          
          <div class="ml-4 text-sm text-gray-500">
            共 {{ total }} 条记录
          </div>
        </div>
      </div>
    </div>
  </div>
</template>